package org.happen.android.app;

import org.happen.android.core.data.DataCache;
import org.happen.android.core.net.AppRequestManager;
import org.liushui.mycommons.android.McApplication;
import org.liushui.mycommons.android.log.McLog;

import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;

public class AppContext extends McApplication implements ILife
{

	public static AppContext instance;
	public SharedPreferences mPreference;

	public static AppContext getInstance()
	{
		return instance;
	}

	AppRequestManager requestControl;
	DataCache dataCache;
	Handler handler;
	LocationClient mLocationClient = null;
	String address;

	public void onCreate()
	{
		super.onCreate();
		instance = this;
		mPreference = PreferenceManager.getDefaultSharedPreferences(this);
		init();
		requestLocation();
	}

	public void init()
	{
		McLog.m(this, "init");
		requestControl = AppRequestManager.getInstance();
		requestControl.init();
		dataCache = DataCache.getInstance();
		dataCache.init();

		mLocationClient = new LocationClient(this); //声明LocationClient类
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);//设置定位模式
		option.setCoorType("bd09ll");//返回的定位结果是百度经纬度，默认值gcj02
		option.setScanSpan(5000);
		//设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);//返回的定位结果包含地址信息
		option.setNeedDeviceDirect(true);//返回的定位结果包含手机机头的方向
		mLocationClient.setLocOption(option);
		mLocationClient.registerLocationListener(new MyLocationListener()); //注册监听函数
	}

	public void requestLocation()
	{
		if (!mLocationClient.isStarted())
		{
			mLocationClient.start();
		}
		if (!mLocationClient.isStarted())
		{
			mLocationClient.requestLocation();
		}
	}

	class MyLocationListener implements BDLocationListener
	{
		public void onReceiveLocation(BDLocation location)
		{
			McLog.m(this, "onReceiveLocation");
			if (location != null)
			{
				McLog.i(location.getAddrStr() + "");
				address = location.getAddrStr();
				if (!TextUtils.isEmpty(address))
				{
					mLocationClient.stop();
				}
			}
		}

		public void onReceivePoi(BDLocation poiLocation)
		{
			McLog.m(this, "onReceivePoi");
			if (poiLocation != null)
			{
				McLog.i(poiLocation.getAddrStr() + "");
				address = poiLocation.getAddrStr();
				if (!TextUtils.isEmpty(address))
				{
					mLocationClient.stop();
				}
			}
		}
	}

	public void unInit()
	{
		McLog.m(this, "unInit");
		dataCache.unInit();
		requestControl.unInit();
	}

	public void onTerminate()
	{
		super.onTerminate();
		unInit();
	}
}